package controller;

import implementor.CustomerInfoImp;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLIntegrityConstraintViolationException;

import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

import daoInterfaces.CustomerInfoDao;

import model.CustomerInfo;
import view.campaign.NewCustomer;

public class NewCustomerController implements ActionListener
{
	NewCustomer view;
	CustomerInfo model;
	
	public NewCustomerController() 
	{
		
	}

	public NewCustomerController(NewCustomer view, CustomerInfo model) {
		super();
		this.view = view;
		this.model = model;
		view.actionListener(this);
	}

	public NewCustomer getView() {
		return view;
	}

	public void setView(NewCustomer view) {
		this.view = view;
	}

	public CustomerInfo getModel() {
		return model;
	}

	public void setModel(CustomerInfo model) {
		this.model = model;
	}
	
	public void reactOnSave()
	{
		String name=view.gettCustName().getText();
		String email=view.gettEmail().getText();
		double ph=Double.parseDouble(view.gettPhone().getText());
		model=new CustomerInfo(0, name, null, null, email, ph);
		
		CustomerInfoDao imp=new CustomerInfoImp();
		try
		{
			imp.add(model);
			JOptionPane.showMessageDialog(null, "Data successfully added");
		}
	
		catch(SQLIntegrityConstraintViolationException e)
		{
			JOptionPane.showMessageDialog(null, "Name already exist, please use another one");
		}
		
		catch(Exception e)
		{
			JOptionPane.showMessageDialog(null, "Data not successfully added,Please try again !");
		
		}	

		CustomerInfoDao cust=new CustomerInfoImp();
		CustomerInfo[] c=cust.retrieveAll();
		DefaultTableModel dm=(DefaultTableModel) view.getTable().getModel();
		for(int i=0;i<c.length;i++)
		{
			dm.addRow(new Object[]{c[i].getName(),c[i].getEmailAdr(),c[i].getPhoneNo()});
		}
		
	}
	
	/*public void reactOnAdd()
	{
		CustomerInfoDao cust=new CustomerInfoImp();
		CustomerInfo[] c=cust.retrieveAll();
		DefaultTableModel dm=(DefaultTableModel) view.getTable().getModel();
		for(int i=0;i<c.length;i++)
		{
			dm.addRow(new Object[]{c[i].getName(),c[i].getEmailAdr(),c[i].getPhoneNo()});
		}
		
	}*/

	@Override
	public void actionPerformed(ActionEvent arg0)
	{
		String k=arg0.getActionCommand();
		if(k.contains("Save"))
		{
			reactOnSave();
		}
		if(k.contains("Send MSG"))
		{
			
		}
		if(k.contains("Send Email"))
		{
			
		}
	
		
	}
	
	
	

}
